package cn.leaf.calculator.resolver;

import cn.leaf.calculator.bean.ParamEntity;

import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * formula resolver
 *
 * @author 李克国
 * @version 1.0.0
 */
public class SpringELFormulaResolver<T> implements FormulaResolver<T> {

    private String formula;

    private List<ParamEntity<T>> result;

    public final String PARAM = "(?<=#\\{#)(.+?)(?=\\})";

    public SpringELFormulaResolver(String formula) {
        this.formula = formula;
    }

    @Override
    public List<ParamEntity<T>> resolve() {
        if (CollectionUtils.isEmpty(result)) {
            resolve(formula);
        }
        return result;
    }

    @Override
    public void refresh() {
        resolve(formula);
    }

    @Override
    public boolean validate() {
        return true;
    }

    private void resolve(String formulaString) {
        Assert.notNull(formulaString, "需要解析的公式不能为空");
        result = new ArrayList<>();
        Matcher matcher = Pattern.compile(PARAM).matcher(formulaString);
        while (matcher.find()) {
            result.add((new ParamEntity<>(matcher.group())));
        }
    }
}
